﻿using System;
using System.Net;
using System.Linq;
using System.Net.Http;
using System.Web.Http.Filters;
using System.Web.Http.Controllers;

namespace Caramel.Web.Http.Filters
{
	public class ValidationActionFilter : ActionFilterAttribute
	{
		public override void OnActionExecuting(HttpActionContext actionContext)
		{
			if (!actionContext.ModelState.IsValid)
			{
				var errors =
					actionContext.
						ModelState.
							Where(e => e.Value.Errors.Any()).
							Select(
								e =>
								new
								{
									Name = e.Key,
									Message = e.Value.Errors.First().ErrorMessage
								}
							).
							ToArray();

				actionContext.Response = actionContext.Request.CreateResponse(HttpStatusCode.BadRequest, errors);
			}
		}
	}
}
